#define _CRT_SECURE_NO_WARNINGS 1

#include"MergeSort.h"

void PrintArray(int* a, int n)
{
	for (int i = 0; i < n; ++i)
	{
		printf("%d  ", a[i]);
	}
	printf("\n");
}

void _MergeSort(int* a, int* tmp,int left, int right)
{
	if (left >= right)
	{
		return ;
	}

	int begin = left;
	int mid = (left + right) / 2;
	int begin1 = left,end1 = mid;
	int begin2 = mid + 1, end2 = right;
	
	_MergeSort(a,tmp,begin1,end1);
	_MergeSort(a,tmp,begin2, end2);

	while(begin1 <= end1 && begin2 <= end2)
	{ 
		if (a[begin1] < a[begin2])
		{
			tmp[begin++] = a[begin1++];
		}
		else
		{
			tmp[begin++] = a[begin2++];
		}
	}

	while (begin1 <= end1)
	{
		tmp[begin++] = a[begin1++];
	}

	while (begin2 <= end2)
	{
		tmp[begin++] = a[begin2++];
	}
	
	memcpy(a + left,tmp + left,sizeof(int) * (right - left + 1));
}

void MergeSort(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
		perror("malloc fail");
		return ;
	}
	_MergeSort(a, tmp, 0, n - 1);

	free(tmp);
	tmp = NULL;
}